<template>
  <div class="dept">
    <pageTable ref="pageTableRef" :pageName="pageName" @add-or-edit="showDialog" :header="headers">
      <template #status="row">
        <t-switch size="large" :defaultValue="!!row.status" @change="updateStatus(row.id)">
          <template #label="{ value }">
            <t-icon name="check" v-if="value" />
            <t-icon name="close" v-else />
          </template>
        </t-switch>
      </template>
    </pageTable>
    <pageDialog
      ref="pageDialogRef"
      :title="`${editId ? '编辑' : '新增'}${pageTitle}`"
      @confirm="confirm"
    >
      <t-form
        ref="formRef"
        labelAlign="top"
        resetType="initial"
        :data="editId ? editForm : addForm"
        :rules="rules"
      >
        <t-form-item label="部门名称" name="name">
          <t-input v-model="(editId ? editForm : addForm).name"></t-input>
        </t-form-item>
      </t-form>
    </pageDialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import pageTable from '@/components/page-table/page-table.vue'
import pageDialog from '@/components/page-dialog/page-dialog.vue'
import useDialog from '@/hooks/useDialog'
import useTable from '@/hooks/useTable'
import useSystemStore from '@/stores/main/system'

const pageName = 'dept'
const pageTitle = '部门'
const systemStore = useSystemStore()

const headers = [
  { colKey: 'name', title: '部门名称', align: 'center', ellipsis: true },
  { colKey: 'status', title: '状态', align: 'center', ellipsis: true },
  { colKey: 'created_at', title: '创建时间', align: 'center', ellipsis: true },
  { colKey: 'updated_at', title: '更新时间', align: 'center', ellipsis: true }
]

const addForm = ref({
  name: ''
})
const editForm = ref({
  name: ''
})
const rules = {
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
}

const { editId, showDialog, formRef, pageDialogRef } = useDialog(editForm)
const { confirm, pageTableRef } = useTable({
  pageName,
  editId,
  editForm,
  addForm,
  formRef,
  pageDialogRef
})

const updateStatus = (id: number) => {
  const queryInfo = {
    page: pageTableRef.value!.pagination.current,
    size: pageTableRef.value!.pagination.pageSize
  }
  systemStore.editStatusAction(pageName, id, queryInfo)
}
</script>
